package com.example.lihaoqian

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class SharedPreferencesUtil(context: Context) {
    private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences("word_prefs", Context.MODE_PRIVATE)
    private val gson = Gson()

    fun saveWordList(wordList: MutableList<String>) {
        val json = gson.toJson(wordList)
        sharedPreferences.edit().putString("word_list", json).apply()
    }

    fun getWordList(): MutableList<String> {
        val json = sharedPreferences.getString("word_list", null)
        return if (json != null) {
            val type = object : TypeToken<MutableList<String>>() {}.type
            gson.fromJson(json, type)
        } else {
            mutableListOf()
        }
    }

    fun addWord(word: String) {
        val wordList = getWordList()
        wordList.add(word)
        saveWordList(wordList)
    }

    fun removeWord(word: String) {
        val wordList = getWordList()
        wordList.remove(word)
        saveWordList(wordList)
    }
}